package com.ruoyi.common.utils.wechatmp;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信消息xml工具类
 *
 * @author xudm
 * @description TODO
 * @date 2024-09-27  17:40
 */
public class WechatMpXmlUtil {
    /**
     * 获取消息类型
     *
     * @author xudm
     * @date 2024/9/27 17:45
     **/
    public static String getMsgType(String xml) {
        Map<String, String> map = parseXml(xml);
        return map.get("MsgType");
    }

    /**
     * 解析微信推送的XML消息
     *
     * @author xudm
     * @date 2024/9/27 17:44
     **/
    public static Map<String, String> parseXml(String xml) {
        Map<String, String> map = new HashMap<>();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
            Element root = document.getDocumentElement();
            NodeList nodeList = root.getChildNodes();

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    map.put(element.getNodeName(), element.getTextContent());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 生成响应的XML消息
     *
     * @author xudm
     * @date 2024/9/27 17:44
     **/
    public static String generateResponseXml(String xml, String responseContent) {
        Map<String, String> message = parseXml(xml);
        String fromUser = message.get("FromUserName");
        String toUser = message.get("ToUserName");

        // 这里可以根据用户发送的内容进行自定义回复
        return String.format(
                "<xml>" +
                        "<ToUserName><![CDATA[%s]]></ToUserName>" +
                        "<FromUserName><![CDATA[%s]]></FromUserName>" +
                        "<CreateTime>%d</CreateTime>" +
                        "<MsgType><![CDATA[text]]></MsgType>" +
                        "<Content><![CDATA[%s]]></Content>" +
                        "</xml>",
                fromUser, toUser, System.currentTimeMillis() / 1000, responseContent);
    }

    public static String sha1(String tmpStr) {
        try {
            // 创建 SHA-256 消息摘要实例
            MessageDigest digest = MessageDigest.getInstance("SHA-1");

            // 计算输入字符串的 SHA-256 散列值
            byte[] hashBytes = digest.digest(tmpStr.getBytes());

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        Map<String, String> parseXml = WechatMpXmlUtil.parseXml("""
                <xml>
                  <ToUserName><![CDATA[toUser]]></ToUserName>
                  <FromUserName><![CDATA[fromUser]]></FromUserName>
                  <CreateTime>1348831860</CreateTime>
                  <MsgType><![CDATA[text]]></MsgType>
                  <Content><![CDATA[this is a test]]></Content>
                  <MsgId>1234567890123456</MsgId>
                  <MsgDataId>xxxx</MsgDataId>
                  <Idx>xxxx</Idx>
                </xml>
                """);
        String s = parseXml.get("Content");
        System.out.println(s);


    }
}
